#!/bin/bash
#
#Purpose: install docker and build jenkins images
#
#Author: wangyd
#
set -e

JENKINS_PORT=8080
JENKINS_SLAVE_PORT=50000
JENKINS_HOME="/var/jenkins_home"
HOST_IP=$(hostname --ip-address)

if command -v docker >/dev/null 2>&1;then
	echo "docker is installed, no need to install it again."
else
	echo "Install docker environment, please wait..."
	# use docker official install script
	/bin/bash src/install_docker.sh --mirror Aliyun >/dev/null
	systemctl start docker
fi
echo "setup docker env..."
if id jenkins >/dev/null 2>&1;then
	echo "user jenkins already exists."
else
	useradd -u 1000 jenkins
fi

[ ! -d $JENKINS_HOME ] && mkdir -p $JENKINS_HOME
chown -R jenkins: $JENKINS_HOME


#change docker registry to China mirror
[ ! -d /etc/docker/ ] && mkdir /etc/docker/
cat > /etc/docker/daemon.json << EOF
{ 
"registry-mirrors":["https://registry.docker-cn.com"] 
}
EOF
systemctl  daemon-reload 
systemctl restart docker


echo "build jenkins docker image"
docker build -t jenkins:wyd src


echo "start jenkins docker image..."
docker run -u root --rm -p $JENKINS_PORT:$JENKINS_PORT -p $JENKINS_SLAVE_PORT:$JENKINS_SLAVE_PORT -v $JENKINS_HOME:$JENKINS_HOME -v /var/run/docker.sock:/var/run/docker.sock -v /root/.m2/:/root/.m2/   -d jenkins:wyd

echo "jenkins startup success, use following message to login"
echo "============================================"
echo "url: http://$HOST_IP:$JENKINS_PORT"
echo "username:admin"
echo "password:admin"
echo "============================================"

